//
//  BK_my_EvaluationOfDryingVC.m
//  bestkeep
//
//  Created by 李明 on 2016/11/30.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BK_my_EvaluationOfDryingVC.h"
#import "BK_my_EvaluationOfDryingCell1.h"
#import "BK_my_EvaluationOfDryingCell2.h"
#import "BK_my_EvaluationOfDryingCell3.h"
#import "Masonry.h"
#import "BKMyCommon.h"

#import "BK_my_evaluationCommon.h"

@interface BK_my_EvaluationOfDryingVC ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>
@property (nonatomic, strong) NSArray <SectionModel *> *sectionDataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *imgUrls;
@property (nonatomic, strong) NSString *score;
@property (nonatomic, copy) NSString *informationText;
@property (nonatomic, strong) UIButton *rightBtn;

@end

@implementation BK_my_EvaluationOfDryingVC

static NSString *evaluationOfDryingCellIdentifier = @"evaluationOfDryingCellIdentifier";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评价晒单";
    _imgUrls = [[NSMutableArray alloc] init];
    [self rightBarButtonItem];
    [self initializeView];
    self.view.backgroundColor = RGBCOLOR(242, 242, 242, 1);
    _score = @"5";
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(notice:) name:@"currentScore" object:nil];
}

-(void)notice:(NSNotification *)sender{
    _score = [NSString stringWithFormat:@"%@",sender.userInfo[@"starCount"]];
}

- (void)dealloc {
    self.tableView.delegate =nil;
    self.tableView.dataSource =nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)rightBarButtonItem {
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame = CGRectMake(0, 0, 33, 30);
    [_rightBtn addTarget:self action:@selector(uploadEvaluatoin) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    _rightBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    _rightBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [_rightBtn setTitleColor:RGBCOLOR(0, 186, 156, 1) forState:UIControlStateNormal];
    [_rightBtn setTitleColor:RGBCOLOR(0, 186, 156, 0.5) forState:UIControlStateHighlighted];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
}

- (void)initializeView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[BK_my_EvaluationOfDryingCell1 class] forCellReuseIdentifier:evaluationOfDryingCellIdentifier];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.top.mas_equalTo(self.view.mas_top).offset(0);
    }];
}

- (NSArray <SectionModel *> *)sectionDataArray {
    CellModel *model1 = [CellModel cellModelWithTitle:nil sel:nil];
    model1.height = 100;
    model1.className = @"BK_my_EvaluationOfDryingCell1";
    model1.reuseIdentifier = @"cell1";
    model1.delegate = self;
    model1.image = self.img;
    model1.title = self.name;
    
    CellModel *model2 = [CellModel cellModelWithTitle:nil sel:nil];
    model2.height = 150;
    model2.className = @"BK_my_EvaluationOfDryingCell2";
    model2.reuseIdentifier = @"cell2";
    model2.delegate = self;
    
    CellModel *model3 = [CellModel cellModelWithTitle:nil sel:nil];
    model3.height = ScreenWidth / 2 + 35;
    model3.className = @"BK_my_EvaluationOfDryingCell3";
    model3.reuseIdentifier = @"cell3";
    model3.delegate = self;
    SectionModel *sectionModel = [SectionModel sectionModelWithTitle:nil cells:@[model1, model2, model3]];
    return @[sectionModel];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    SectionModel *section = self.sectionDataArray[0];
    return section.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *section = self.sectionDataArray[0];
    CellModel *cellModel = section.cells[indexPath.section];
    return cellModel.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2) {
        return 10;
    } else {
        return .5f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *sectionModel = self.sectionDataArray[indexPath.row];
    CellModel *row = sectionModel.cells[indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:row.reuseIdentifier];
    if (cell == nil) {
                cell = [[NSClassFromString(row.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:row.reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *sectionModel = self.sectionDataArray[indexPath.row];
    CellModel *cellModel = sectionModel.cells[indexPath.section];
    if ([cell respondsToSelector:@selector(initializeCell:)]) {
        [cell performSelector:@selector(initializeCell:) withObject:cellModel];
    }
}

- (void)uploadEvaluatoin {
    BK_my_EvaluationOfDryingCell2 *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    _informationText = [NSString stringWithFormat:@"%@", cell2.informationTextView.text];
    
    if ([self isRightStyleWithContent]) {
        return;
    }
    [self uploadEvaluatoinToServer];
}

- (void)uploadEvaluatoinToServer {
    
    [self.view endEditing:YES];
    _rightBtn.enabled = NO;
    BK_my_EvaluationOfDryingCell3 *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    [BKIndicationView showInView:self.view];
    if (cell.photos.count == 0) {
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        //                    订单号
        [dic setObject:self.order_id forKey:@"orderId"];
        //                    订单子项表Id
        [dic setObject:self.order_item_id  forKey:@"orderItemId"];
        //                    订单ID
        [dic setObject:self.goodsId forKey:@"goodsId"];
        //                    图片地址
        [dic setObject:[_imgUrls componentsJoinedByString:@";"] forKey:@"images"];
        [dic setObject:_informationText forKey:@"experiences"];
        [dic setObject:_score forKey:@"scoringGrades"];
        
        [BK_my_evaluationCommon uploadEvaluationToServiceForDict:dic callBack:^(id obj, NSError *error) {
            _rightBtn.enabled = YES;
            [BKIndicationView dismiss];
            [self.imgUrls removeAllObjects];
            if (obj) {
                BOOL success = [obj[@"success"] boolValue];
                if(success) {
                    [HUD showSuccessMessage:@"评价成功"];
                    if (_reloadData)
                    {
                        _reloadData(@"YES");
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [HUD showMessage:obj[@"msg"]];
                }
            }else {
                if (error.code==502) {
                    [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                }else{
                    [HUD showErrorMessage:error.localizedDescription];
                }
                
            }
        }];
    } else {
        
        for (UIImage *image in cell.photos) {
            CGFloat compressionQuality;
            if(image.size.height > 3000 || image.size.width > 3000) {
                compressionQuality = 0.3;
            } else if (image.size.height > 1500 || image.size.width > 1500){
                compressionQuality = 0.5;
            } else {
                compressionQuality = 0.8;
            }
            NSData *imgData = UIImageJPEGRepresentation(image, compressionQuality);
            
            [BK_my_evaluationCommon uploadEvaluationImgToServiceForData:imgData callback:^(id obj, NSError *error) {
                
                if (obj) {
                    BOOL success = [obj[@"success"] boolValue];
                    if(success == YES) {
                        
                        [_imgUrls addObject:[obj objectForKey:@"urls"]];
                        if (self.imgUrls.count == cell.photos.count) {
                            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                            [dict setObject:self.order_id forKey:@"orderId"];
                            [dict setObject:self.order_item_id forKey:@"orderItemId"];
                            [dict setObject:self.goodsId forKey:@"goodsId"];
                            [dict setObject:[_imgUrls componentsJoinedByString:@";"] forKey:@"images"];
                            [dict setObject:_informationText forKey:@"experiences"];
                            [dict setObject:_score forKey:@"scoringGrades"];
                            [BK_my_evaluationCommon uploadEvaluationToServiceForDict:dict callBack:^(id obj, NSError *error) {
                                
                                _rightBtn.enabled = YES;
                                [BKIndicationView dismiss];
                                [self.imgUrls removeAllObjects];
                                if (obj) {
                                    BOOL success = [obj[@"success"] boolValue];
                                    if(success == YES) {
                                        [HUD showSuccessMessage:@"评价成功"];
                                        if (_reloadData)
                                        {
                                            _reloadData(@"YES");
                                        }
                                        [self.navigationController popViewControllerAnimated:YES];
                                    } else {
                                        [HUD showMessage:obj[@"msg"]];
                                    }
                                }else {
                                    if (error.code==502) {
                                        [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                                    }else{
                                        [HUD showErrorMessage:error.localizedDescription];
                                    }
                                }
                            }];
                        }
                    }else {
                        [BKIndicationView dismiss];
                        [HUD showMessage:obj[@"msg"]];
                    }
                }else {
                    [BKIndicationView dismiss];
                    if (error.code==502) {
                        [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
                    }else{
                        [HUD showErrorMessage:error.localizedDescription];
                    }
                    
                }
            }];
        }
    }

}

//检验输入内容
-(BOOL)isRightStyleWithContent {
    if ([_score isEqualToString:@"0"]) {
        [HUD showMessage:@"评分至少一颗星"];
        return YES;
    }
    if ([_informationText isEqualToString:@""] || [_informationText isEqualToString:@"长度在10-500字之间,写下购买体会可以为其他小伙伴提供参考"]) {
        [HUD showMessage:@"您还未填写评论哦"];
        return YES;
    }
    if (_informationText.length < 10) {
        [HUD showMessage:@"评论字数不足10字"];
        return YES;
    }
    if (_informationText.length > 500) {
        [HUD showMessage:@"评论字数超出限制"];
        return YES;
    }
    //特殊字符过滤
    NSString *passwordStandard = @"^[(0-9)|(\u4e00-\u9fa5)|(A-Za-z0-9\u4e00-\u9fa5)|(@)|(!)|(#)|(+)|(-)|(%)|(,)|(<)|(，)|(。)|(.)|(/)|(?)|(;)|(；)|(：)|(:)|({)|([)|(])|(})|(*)|(~)|(`)|(·)|(《)|(》)|(>)|(？)|(“)|(&)|(……)|(…)|(^)|( )|(！)|(')|(”)|($)|(￥)|(（)|(）)]+$";
    NSRegularExpression *regexpasswordStandard = [NSRegularExpression regularExpressionWithPattern:passwordStandard options:0 error:nil];
    NSTextCheckingResult *isMatchpasswordStandard = [regexpasswordStandard firstMatchInString:_informationText options:0 range:NSMakeRange(0,[_informationText length])];
    if (!isMatchpasswordStandard) {
        [self showSpecialCharacterAlertView];
        return YES;
    }
    return NO;
}

- (void)showSpecialCharacterAlertView {
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"含有特殊字符，可能评价失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alertView.tag = 111001;
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 111001) {
        [self uploadEvaluatoinToServer];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
